import 'package:flutter/material.dart';
import 'package:flutter_bilibili/pages/Ranking_page.dart';
import 'package:flutter_bilibili/pages/favorite_page.dart';
import 'package:flutter_bilibili/pages/home_page.dart';
import 'package:flutter_bilibili/pages/profile_page.dart';
import 'package:flutter_bilibili/util/color_util.dart';
import 'package:flutter_bilibili/widget/loading_container.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  bool isLoading = true;
  final defaultColor = Colors.grey;
  final activeColor = primary;
  int currentIndex = 0;
  final PageController controller = PageController(initialPage: 0);
  List<Widget> list = [];
  final List<Map<String, dynamic>> titleList = const [
    {'title': '首页', 'icon': Icons.home},
    {'title': '排行', 'icon': Icons.local_fire_department},
    {'title': '收藏', 'icon': Icons.favorite},
    {'title': '我的', 'icon': Icons.live_tv}
  ];

  @override
  void initState() {
    super.initState();
    list = [
      HomePage(toProfilePage: () {
        // 跳转到“我的”tab页
        setCurIndex(3);
      }),
      const RankingPage(),
      const FavoritePage(),
      const ProfilePage()
    ];
    Future.delayed(const Duration(seconds: 1), () {
      setState(() {
        isLoading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return LoadingContainer(
      isLoading: isLoading,
      child: Scaffold(
        body: PageView.builder(
          itemBuilder: (context, index) => list[currentIndex],
          controller: controller,
          itemCount: list.length,
          onPageChanged: setCurIndex,
          // physics: const NeverScrollableScrollPhysics(), // 禁止滚动
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: currentIndex,
          onTap: setCurIndex,
          type: BottomNavigationBarType.fixed,
          items: titleList
              .map((item) => _bottomItem(item['title'], item['icon']))
              .toList(),
        ),
      ),
    );
  }

  setCurIndex(index) {
    setState(() {
      currentIndex = index;
    });
  }

  BottomNavigationBarItem _bottomItem(String label, IconData icon) {
    return BottomNavigationBarItem(
      icon: Icon(icon, color: defaultColor),
      label: label,
      activeIcon: Icon(icon, color: activeColor),
    );
  }
}
